home *** CD-ROM | disk | FTP | other *** search
/ MPEG Toolkit / MPEG Toolkit.iso / dos / ampeg43 / source / encodsrc / musicin.c < prev    next >
Encoding:
C/C++ Source or Header  |  1997-01-01  |  36.1 KB  |  1,011 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. musicin.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 4.0                                                        *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers         comment                               *
  14.  * 3/01/91  Douglas Wong,       start of version 1.1 records          *
  15.  *          Davis Pan                                                 *
  16.  * 3/06/91  Douglas Wong,       rename: setup.h to endef.h            *
  17.  *                              removed extraneous variables          *
  18.  * 3/21/91  J.Georges Fritsch   introduction of the bit-stream        *
  19.  *                              package. This package allows you      *
  20.  *                              to generate the bit-stream in a       *
  21.  *                              binary or ascii format                *
  22.  * 3/31/91  Bill Aspromonte     replaced the read of the SB matrix    *
  23.  *                              by an "code generated" one            *
  24.  * 5/10/91  W. Joseph Carter    Ported to Macintosh and Unix.         *
  25.  *                              Incorporated Jean-Georges Fritsch's   *
  26.  *                              "bitstream.c" package.                *
  27.  *                              Modified to strictly adhere to        *
  28.  *                              encoded bitstream specs, including    *
  29.  *                              "Berlin changes".                     *
  30.  *                              Modified user interface dialog & code *
  31.  *                              to accept any input & output          *
  32.  *                              filenames desired.  Also added        *
  33.  *                              de-emphasis prompt and final bail-out *
  34.  *                              opportunity before encoding.          *
  35.  *                              Added AIFF PCM sound file reading     *
  36.  *                              capability.                           *
  37.  *                              Modified PCM sound file handling to   *
  38.  *                              process all incoming samples and fill *
  39.  *                              out last encoded frame with zeros     *
  40.  *                              (silence) if needed.                  *
  41.  *                              Located and fixed numerous software   *
  42.  *                              bugs and table data errors.           *
  43.  * 27jun91  dpwe (Aware Inc)    Used new frame_params struct.         *
  44.  *                              Clear all automatic arrays.           *
  45.  *                              Changed some variable names,          *
  46.  *                              simplified some code.                 *
  47.  *                              Track number of bits actually sent.   *
  48.  *                              Fixed padding slot, stereo bitrate    *
  49.  *                              Added joint-stereo : scales L+R.      *
  50.  * 6/12/91  Earle Jennings      added fix for MS_DOS in obtain_param  *
  51.  * 6/13/91  Earle Jennings      added stack length adjustment before  *
  52.  *                              main for MS_DOS                       *
  53.  * 7/10/91  Earle Jennings      conversion of all float to FLOAT      *
  54.  *                              port to MsDos from MacIntosh completed*
  55.  * 8/ 8/91  Jens Spille         Change for MS-C6.00                   *
  56.  * 8/22/91  Jens Spille         new obtain_parameters()               *
  57.  *10/ 1/91  S.I. Sudharsanan,   Ported to IBM AIX platform.           *
  58.  *          Don H. Lee,                                               *
  59.  *          Peter W. Farrett                                          *
  60.  *10/ 3/91  Don H. Lee          implemented CRC-16 error protection   *
  61.  *                              newly introduced functions are        *
  62.  *                              I_CRC_calc, II_CRC_calc and encode_CRC*
  63.  *                              Additions and revisions are marked    *
  64.  *                              with "dhl" for clarity                *
  65.  *11/11/91 Katherine Wang       Documentation of code.                *
  66.  *                                (variables in documentation are     *
  67.  *                                surround by the # symbol, and an '*'*
  68.  *                                denotes layer I or II versions)     *
  69.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  70.  *                              important fixes involved changing     *
  71.  *                              16-bit ints to long or unsigned in    *
  72.  *                              bit alloc routines for quant of 65535 *
  73.  *                              and passing proper function args.     *
  74.  *                              Removed "Other Joint Stereo" option   *
  75.  *                              and made bitrate be total channel     *
  76.  *                              bitrate, irrespective of the mode.    *
  77.  *                              Fixed many small bugs & reorganized.  *
  78.  * 2/25/92  Masahiro Iwadare    made code cleaner and more consistent *
  79.  * 8/07/92  Mike Coleman        make exit() codes return error status *
  80.  *                              made slight changes for portability   *
  81.  *19 aug 92 Soren H. Nielsen    Changed MS-DOS file name extensions.  *
  82.  * 8/25/92  Shaun Astarabadi    Replaced rint() function with explicit*
  83.  *                              rounding for portability with MSDOS.  *
  84.  * 9/22/92  jddevine@aware.com  Fixed _scale_factor_calc() calls.     *
  85.  *10/19/92  Masahiro Iwadare    added info->mode and info->mode_ext   *
  86.  *                              updates for AIFF format files         *
  87.  * 3/10/93  Kevin Peterson      In parse_args, only set non default   *
  88.  *                              bit rate if specified in arg list.    *
  89.  *                              Use return value from aiff_read_hdrs  *
  90.  *                              to fseek to start of sound data       *
  91.  * 7/26/93  Davis Pan           fixed bug in printing info->mode_ext  *
  92.  *                              value for joint stereo condition      *
  93.  * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
  94.  *         Daniel Lauzon, and                                         *
  95.  *         Bill Truerniet                                             *
  96.  **********************************************************************/
  97.  
  98.  
  99. #include <dos.h>
  100. #include "common.h"
  101. #include "encoder.h"
  102.  
  103. /* Global variable definitions for "musicin.c" */
  104.  
  105. FILE               *musicin;
  106. Bit_stream_struc   bs;
  107. char               *programName;
  108.  
  109. /* Implementations */
  110.  
  111. /************************************************************************
  112. /*
  113. /* obtain_parameters
  114. /*
  115. /* PURPOSE:  Prompts for and reads user input for encoding parameters
  116. /*
  117. /* SEMANTICS:  The parameters read are:
  118. /* - input and output filenames
  119. /* - sampling frequency (if AIFF file, will read from the AIFF file header)
  120. /* - layer number
  121. /* - mode (stereo, joint stereo, dual channel or mono)
  122. /* - psychoacoustic model (I or II)
  123. /* - total bitrate, irrespective of the mode
  124. /* - de-emphasis, error protection, copyright and original or copy flags
  125. /*
  126. /************************************************************************/
  127.  
  128. void
  129. obtain_parameters(fr_ps,psy,num_samples,original_file_name,encoded_file_name)
  130. frame_params    *fr_ps;
  131. int             *psy;
  132. unsigned long   *num_samples;
  133. char            original_file_name[MAX_NAME_SIZE];
  134. char            encoded_file_name[MAX_NAME_SIZE];
  135.  
  136. {
  137.     int j;
  138.     int x;
  139.     char default_file_name[MAX_NAME_SIZE];
  140.     long int freq;
  141.     int model, brt;
  142.     char t[50];
  143.     IFF_AIFF pcm_aiff_data;
  144.     layer *info = fr_ps->header;
  145.     long soundPosition;
  146.  
  147.     do  {
  148.        printf("Enter PCM input file name <required>: ");
  149.        gets(original_file_name);
  150.        if (original_file_name[0] == NULL_CHAR)
  151.        printf("PCM input file name is required.\n");
  152.     } while (original_file_name[0] == NULL_CHAR);
  153.     printf(">>> PCM input file name is: %s\n", original_file_name);
  154.  
  155.     if ((musicin = fopen(original_file_name, "rb")) == NULL) {
  156.        printf("Could not find \"%s\".\n", original_file_name);
  157.        exit(1);
  158.     }
  159.     x=0;
  160.     while (x <= MAX_NAME_SIZE)
  161.     {
  162.     default_file_name[x] = NULL_CHAR;
  163.     ++x;
  164.     }
  165.     x=0;
  166.     while (x <= 8)
  167.     {
  168.    default_file_name[x] = original_file_name[x];
  169.     if (original_file_name[++x] == '.') 
  170.     x = 9;
  171.   
  172.     }
  173.    
  174.     strcat(default_file_name,DFLT_EXT);
  175.  
  176.     printf("Enter MPEG encoded output file name <%s>: ",
  177.        default_file_name); /* 92-08-19 shn */
  178.     gets(encoded_file_name);
  179.     if (encoded_file_name[0] == NULL_CHAR) {
  180.  
  181.     /* replace old extension with new one, 92-08-19 shn */
  182.        strcpy(encoded_file_name,default_file_name);
  183. /*
  184.     strcat(strcpy(encoded_file_name, original_file_name), DFLT_EXT);
  185. */ 
  186.     }
  187.        
  188.  
  189.     printf(">>> MPEG encoded output file name is: %s\n", encoded_file_name);
  190.  
  191.     open_bit_stream_w(&bs, encoded_file_name, BUFFER_SIZE);
  192.  
  193.     if ((soundPosition = aiff_read_headers(musicin, &pcm_aiff_data)) != -1) {
  194.  
  195.        printf(">>> Using Audio IFF sound file headers\n");
  196.  
  197.        aiff_check(original_file_name, &pcm_aiff_data);
  198.  
  199.        if (fseek(musicin, soundPosition, SEEK_SET) != 0) {
  200.       printf("Could not seek to PCM sound data in \"%s\".\n",
  201.          original_file_name);
  202.       exit(1);
  203.        }
  204.  
  205.        info->sampling_frequency = SmpFrqIndex((long)pcm_aiff_data.sampleRate);
  206.        printf(">>> %.f Hz sampling frequency selected\n",
  207.           pcm_aiff_data.sampleRate);
  208.  
  209.        /* Determine number of samples in sound file */
  210. #ifndef MS_DOS
  211.        *num_samples = pcm_aiff_data.numChannels *
  212.               pcm_aiff_data.numSampleFrames;
  213. #else
  214.        *num_samples = (long)(pcm_aiff_data.numChannels) *
  215.               (long)(pcm_aiff_data.numSampleFrames);
  216. #endif
  217.  
  218.     }
  219.     else {    /* Not using Audio IFF sound file headers. */
  220.  
  221.        printf("What is the sampling frequency? <44100>[Hz]: ");
  222.        gets(t);
  223.        freq = atol(t);
  224.        switch (freq) {
  225.       case 48000 : info->sampling_frequency = 1;
  226.           printf(">>> %ld Hz sampling freq selected\n", freq);
  227.           break;
  228.       case 44100 : info->sampling_frequency = 0;
  229.           printf(">>> %ld Hz sampling freq selected\n", freq);
  230.           break;
  231.       case 32000 : info->sampling_frequency = 2;
  232.           printf(">>> %ld Hz sampling freq selected\n", freq);
  233.           break;
  234.       default:    info->sampling_frequency = 0;
  235.           printf(">>> Default 44.1 kHz samp freq selected\n");
  236.        }
  237.  
  238.        if (fseek(musicin, 0, SEEK_SET) != 0) {
  239.       printf("Could not seek to PCM sound data in \"%s\".\n",
  240.           original_file_name);
  241.       exit(1);
  242.        }
  243.  
  244.        /* Declare sound file to have "infinite" number of samples. */
  245.        *num_samples = MAX_U_32_NUM;
  246.  
  247.     }
  248.  
  249.     printf("Which layer do you want to use?\n");
  250.     printf("Available: Layer (1), Layer (<2>): ");
  251.     gets(t);
  252.     switch(*t){
  253.        case '1': info->lay = 1; printf(">>> Using Layer %s\n",t); break;
  254.        case '2': info->lay = 2; printf(">>> Using Layer %s\n",t); break;
  255.        default:  info->lay = 2; printf(">>> Using default Layer 2\n"); break;
  256.     }
  257.  
  258.     printf("Which mode do you want?\n");
  259.     printf("Available: (<s>)tereo, (j)oint stereo, ");
  260.     printf("(d)ual channel, s(i)ngle Channel: ");
  261.     gets(t);
  262.     switch(*t){
  263.        case 's':
  264.        case 'S':
  265.       info->mode = MPG_MD_STEREO; info->mode_ext = 0;
  266.       printf(">>> Using mode %s\n",t);
  267.       break;
  268.        case 'j':
  269.        case 'J':
  270.       info->mode = MPG_MD_JOINT_STEREO;
  271.       printf(">>> Using mode %s\n",t);
  272.       break;
  273.        case 'd':
  274.        case 'D':
  275.       info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext = 0;
  276.       printf(">>> Using mode %s\n",t);
  277.       break;
  278.        case 'i':
  279.        case 'I':
  280.       info->mode = MPG_MD_MONO; info->mode_ext = 0;
  281.       printf(">>> Using mode %s\n",t);
  282.       break;
  283.        default:
  284.       info->mode = MPG_MD_STEREO; info->mode_ext = 0;
  285.       printf(">>> Using default stereo mode\n");
  286.       break;
  287.     }
  288.  
  289.     printf("Which psychoacoustic model do you want to use? <2>: ");
  290.     gets(t);
  291.     model = atoi(t);
  292.     if (model > 2 || model < 1) {
  293.        printf(">>> Default model 2 selected\n");
  294.        *psy = 2;
  295.     }
  296.     else {
  297.        *psy = model;
  298.        printf(">>> Using psychoacoustic model %d\n", model);
  299.     }
  300.  
  301.     printf("What is the total bitrate? <%u>[kbps]: ", DFLT_BRT);
  302.     gets(t);
  303.     brt = atoi(t);
  304.     if (brt == 0) brt = -10;
  305.     j=0;
  306.     while (j<15) {
  307.        if (bitrate[info->lay-1][j] == brt) break;
  308.        j++;
  309.     }
  310.     if (j==15) {
  311.        printf(">>> Using default %u kbps\n", DFLT_BRT);
  312.        for (j=0;j<15;j++)
  313.       if (bitrate[info->lay-1][j] == DFLT_BRT) {
  314.          info->bitrate_index = j;
  315.          break;
  316.       }
  317.     }
  318.     else{
  319.        info->bitrate_index = j;
  320.        printf(">>> Bitrate = %d kbps\n", bitrate[info->lay-1][j]);
  321.     }
  322.  
  323.     printf("What type of de-emphasis should the decoder use?\n");
  324.     printf("Available: (<n>)one, (5)0/15 microseconds, (c)citt j.17: ");
  325.     gets(t);
  326.     if (*t != 'n' && *t != '5' && *t != 'c') {
  327.        printf(">>> Using default no de-emphasis\n");
  328.        info->emphasis = 0;
  329.     }
  330.     else {
  331.        if (*t == 'n')      info->emphasis = 0;
  332.        else if (*t == '5') info->emphasis = 1;
  333.        else if (*t == 'c') info->emphasis = 3;
  334.        printf(">>> Using de-emphasis %s\n",t);
  335.     }
  336.  
  337. /*  Start 2. Part changes for CD Ver 3.2; jsp; 22-Aug-1991 */
  338.  
  339.     printf("Do you want to set the private bit? (y/<n>): ");
  340.     gets(t);
  341.     if (*t == 'y' || *t == 'Y') info->extension = 1;
  342.     else                        info->extension = 0;
  343.     if(info->extension) printf(">>> Private bit set\n");
  344.     else                printf(">>> Private bit not set\n");
  345.  
  346. /*  End changes for CD Ver 3.2; jsp; 22-Aug-1991 */
  347.  
  348.     printf("Do you want error protection? (y/<n>): ");
  349.     gets(t);
  350.     if (*t == 'y' || *t == 'Y') info->error_protection = TRUE;
  351.     else                        info->error_protection = FALSE;
  352.     if(info->error_protection) printf(">>> Error protection used\n");
  353.     else printf(">>> Error protection not used\n");
  354.  
  355.     printf("Is the material copyrighted? (y/<n>): ");
  356.     gets(t);
  357.     if (*t == 'y' || *t == 'Y') info->copyright = 1;
  358.     else                        info->copyright = 0;
  359.     if(info->copyright) printf(">>> Copyrighted material\n");
  360.     else                printf(">>> Material not copyrighted\n");
  361.  
  362.     printf("Is this the original? (y/<n>): ");
  363.     gets(t);
  364.     if (*t == 'y' || *t == 'Y') info->original = 1;
  365.     else                        info->original = 0;
  366.     if(info->original) printf(">>> Original material\n");
  367.     else               printf(">>> Material not original\n");
  368.  
  369.     printf("Do you wish to exit (last chance before encoding)? (y/<n>): ");
  370.     gets(t);
  371.     if (*t == 'y' || *t == 'Y') exit(0);
  372. }
  373.  
  374. /************************************************************************
  375. /*
  376. /* parse_args
  377. /*
  378. /* PURPOSE:  Sets encoding parameters to the specifications of the
  379. /* command line.  Default settings are used for parameters
  380. /* not specified in the command line.
  381. /*
  382. /* SEMANTICS:  The command line is parsed according to the following
  383. /* syntax:
  384. /*
  385. /* -l  is followed by the layer number
  386. /* -m  is followed by the mode
  387. /* -p  is followed by the psychoacoustic model number
  388. /* -s  is followed by the sampling rate
  389. /* -b  is followed by the total bitrate, irrespective of the mode
  390. /* -d  is followed by the emphasis flag
  391. /* -c  is followed by the copyright/no_copyright flag
  392. /* -o  is followed by the original/not_original flag
  393. /* -e  is followed by the error_protection on/off flag
  394. /*
  395. /* If the input file is in AIFF format, the sampling frequency is read
  396. /* from the AIFF header.
  397. /*
  398. /* The input and output filenames are read into #inpath# and #outpath#.
  399. /*
  400. /************************************************************************/
  401.  
  402. void
  403. parse_args(argc, argv, fr_ps, psy, num_samples, inPath, outPath)
  404. int     argc;
  405. char    **argv;
  406. frame_params  *fr_ps;
  407. int     *psy;
  408. unsigned long *num_samples;
  409. char    inPath[MAX_NAME_SIZE];
  410. char    outPath[MAX_NAME_SIZE];
  411. {
  412.    FLOAT srate;
  413.    int   brate;
  414.    layer *info = fr_ps->header;
  415.    int   err = 0, i = 0;
  416.    IFF_AIFF pcm_aiff_data;
  417.    long samplerate;
  418.    long soundPosition;
  419.  
  420.    /* preset defaults */
  421.    inPath[0] = '\0';   outPath[0] = '\0';
  422.    info->lay = DFLT_LAY;
  423.    switch(DFLT_MOD) {
  424.       case 's': info->mode = MPG_MD_STEREO; info->mode_ext = 0; break;
  425.       case 'd': info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext=0; break;
  426.       case 'j': info->mode = MPG_MD_JOINT_STEREO; break;
  427.       case 'm': info->mode = MPG_MD_MONO; info->mode_ext = 0; break;
  428.       default:
  429.      fprintf(stderr, "%s: Bad mode dflt %c\n", programName, DFLT_MOD);
  430.      abort();
  431.    }
  432.    *psy = DFLT_PSY;
  433.    if((info->sampling_frequency = SmpFrqIndex((long)(1000*DFLT_SFQ))) < 0) {
  434.       fprintf(stderr, "%s: bad sfrq default %.2f\n", programName, DFLT_SFQ);
  435.       abort();
  436.    }
  437.    if((info->bitrate_index = BitrateIndex(info->lay, DFLT_BRT)) < 0) {
  438.       fprintf(stderr, "%s: bad default bitrate %u\n", programName, DFLT_BRT);
  439.       abort();
  440.    }
  441.    switch(DFLT_EMP) {
  442.       case 'n': info->emphasis = 0; break;
  443.       case '5': info->emphasis = 1; break;
  444.       case 'c': info->emphasis = 3; break;
  445.       default: 
  446.      fprintf(stderr, "%s: Bad emph dflt %c\n", programName, DFLT_EMP);
  447.      abort();
  448.    }
  449.    info->copyright = 0; info->original = 0; info->error_protection = FALSE;
  450.  
  451.    /* process args */
  452.    while(++i<argc && err == 0) {
  453.       char c, *token, *arg, *nextArg;
  454.       int  argUsed;
  455.  
  456.       token = argv[i];
  457.       if(*token++ == '-') {
  458.      if(i+1 < argc) nextArg = argv[i+1];
  459.      else           nextArg = "";
  460.      argUsed = 0;
  461.      while(c = *token++) {
  462.         if(*token /* NumericQ(token) */) arg = token;
  463.         else                             arg = nextArg;
  464.         switch(c) {
  465.            case 'l':        info->lay = atoi(arg); argUsed = 1;
  466.           if(info->lay<1 || info->lay>2) {
  467.              fprintf(stderr,"%s: -l layer must be 1 or 2, not %s\n",
  468.               programName, arg);
  469.              err = 1;
  470.           }
  471.           break;
  472.            case 'm':        argUsed = 1;
  473.           if (*arg == 's')
  474.             { info->mode = MPG_MD_STEREO; info->mode_ext = 0; }
  475.           else if (*arg == 'd')
  476.             { info->mode = MPG_MD_DUAL_CHANNEL; info->mode_ext=0; }
  477.           else if (*arg == 'j')
  478.             { info->mode = MPG_MD_JOINT_STEREO; }
  479.           else if (*arg == 'm')
  480.             { info->mode = MPG_MD_MONO; info->mode_ext = 0; }
  481.           else {
  482.             fprintf(stderr,"%s: -m mode must be s/d/j/m not %s\n",
  483.                 programName, arg);
  484.             err = 1;
  485.           }
  486.           break;
  487.            case 'p':        *psy = atoi(arg); argUsed = 1;
  488.           if(*psy<1 || *psy>2) {
  489.              fprintf(stderr,"%s: -p model must be 1 or 2, not %s\n",
  490.                  programName, arg);
  491.              err = 1;
  492.           }
  493.           break;
  494.  
  495.            case 's':
  496.           argUsed = 1;
  497.           srate = atof( arg );
  498.           /* samplerate = rint( 1000.0 * srate ); $A  */
  499.           samplerate = (long) (( 1000.0 * srate ) + 0.5);
  500.           if( (info->sampling_frequency = SmpFrqIndex((long) samplerate)) < 0 )
  501.               err = 1;
  502.           break;
  503.           
  504.            case 'b':        
  505.           argUsed = 1;
  506.           brate = atoi(arg); 
  507.           if( (info->bitrate_index = BitrateIndex(info->lay, brate)) < 0)
  508.              err=1;                  
  509.          break;
  510.            case 'd':        argUsed = 1;
  511.           if (*arg == 'n')                    info->emphasis = 0;
  512.           else if (*arg == '5')               info->emphasis = 1;
  513.           else if (*arg == 'c')               info->emphasis = 3;
  514.           else {
  515.              fprintf(stderr,"%s: -d emp must be n/5/c not %s\n",
  516.                  programName, arg);
  517.              err = 1;
  518.           }
  519.           break;
  520.         case 'c':       info->copyright = 1; break;
  521.         case 'o':       info->original  = 1; break;
  522.         case 'e':       info->error_protection = TRUE; break;
  523.         default:        fprintf(stderr,"%s: unrec option %c\n",
  524.                     programName, c);
  525.                 err = 1; break;
  526.         }
  527.         if(argUsed) {
  528.            if(arg == token)    token = "";   /* no more from token */
  529.            else                ++i;          /* skip arg we used */
  530.            arg = ""; argUsed = 0;
  531.         }
  532.      }
  533.       }
  534.       else {
  535.      if(inPath[0] == '\0')       strcpy(inPath, argv[i]);
  536.      else if(outPath[0] == '\0') strcpy(outPath, argv[i]);
  537.      else {
  538.         fprintf(stderr,"%s: excess arg %s\n", programName, argv[i]);
  539.         err = 1;
  540.      }
  541.       }
  542.    }
  543.  
  544.    if(err || inPath[0] == '\0') usage();  /* never returns */
  545.  
  546.    if(outPath[0] == '\0') {
  547.       strcpy(outPath, inPath);
  548.       strcat(outPath, DFLT_EXT);
  549.    }
  550.  
  551.    if ((musicin = fopen(inPath, "rb")) == NULL) {
  552.       printf("Could not find \"%s\".\n", inPath);
  553.       exit(1);
  554.    }
  555.  
  556.    open_bit_stream_w(&bs, outPath, BUFFER_SIZE);
  557.  
  558.    if ((soundPosition = aiff_read_headers(musicin, &pcm_aiff_data)) != -1) {
  559.  
  560.       printf(">>> Using Audio IFF sound file headers\n");
  561.  
  562.       aiff_check(inPath, &pcm_aiff_data);
  563.  
  564.       if (fseek(musicin, soundPosition, SEEK_SET) != 0) {
  565.      printf("Could not seek to PCM sound data in \"%s\".\n", inPath);
  566.      exit(1);
  567.       }
  568.  
  569.       info->sampling_frequency = SmpFrqIndex((long)pcm_aiff_data.sampleRate);
  570.       printf(">>> %.f Hz sampling frequency selected\n",
  571.          pcm_aiff_data.sampleRate);
  572.  
  573.       /* Determine number of samples in sound file */
  574. #ifndef MS_DOS
  575.       *num_samples = pcm_aiff_data.numChannels *
  576.              pcm_aiff_data.numSampleFrames;
  577. #else
  578.       *num_samples = (long)(pcm_aiff_data.numChannels) *
  579.              (long)(pcm_aiff_data.numSampleFrames);
  580. #endif
  581.       if ( pcm_aiff_data.numChannels == 1 ) {
  582.     info->mode = MPG_MD_MONO;
  583.     info->mode_ext = 0;
  584.       }
  585.    }
  586.    else {    /* Not using Audio IFF sound file headers. */
  587.  
  588.       if (fseek(musicin, 0, SEEK_SET) != 0) {
  589.      printf("Could not seek to PCM sound data in \"%s\".\n", inPath);
  590.      exit(1);
  591.       }
  592.  
  593.       /* Declare sound file to have "infinite" number of samples. */
  594.       *num_samples = MAX_U_32_NUM;
  595.  
  596.    }
  597.  
  598. }
  599.  
  600. /************************************************************************
  601. /*
  602. /* print_config
  603. /*
  604. /* PURPOSE:  Prints the encoding parameters used
  605. /*
  606. /************************************************************************/
  607.  
  608. void
  609. print_config(fr_ps, psy, num_samples, inPath, outPath)
  610. frame_params *fr_ps;
  611. int     *psy;
  612. unsigned long *num_samples;
  613. char    inPath[MAX_NAME_SIZE];
  614. char    outPath[MAX_NAME_SIZE];
  615. {
  616.  layer *info = fr_ps->header;
  617.  
  618.    printf("Encoding configuration:\n");
  619.    if(info->mode != MPG_MD_JOINT_STEREO)
  620.       printf("Layer=%s   mode=%s   extn=%d   psy model=%d\n",
  621.          layer_names[info->lay-1], mode_names[info->mode],
  622.          info->mode_ext, *psy);
  623.    else printf("Layer=%s   mode=%s   extn=data dependant   psy model=%d\n",
  624.            layer_names[info->lay-1], mode_names[info->mode], *psy);
  625.    printf("samp frq=%.1f kHz   total bitrate=%d kbps\n",
  626.       s_freq[info->sampling_frequency],
  627.       bitrate[info->lay-1][info->bitrate_index]);
  628.    printf("de-emph=%d   c/right=%d   orig=%d   errprot=%d\n",
  629.       info->emphasis, info->copyright, info->original,
  630.       info->error_protection);
  631.    printf("input file: '%s'   output file: '%s'\n", inPath, outPath);
  632. }
  633.  
  634. /************************************************************************
  635. /*
  636. /* main
  637. /*
  638. /* PURPOSE:  MPEG I Encoder supporting layers 1 and 2, and
  639. /* psychoacoustic models 1 (MUSICAM) and 2 (AT&T)
  640. /*
  641. /* SEMANTICS:  One overlapping frame of audio of up to 2 channels are
  642. /* processed at a time in the following order:
  643. /* (associated routines are in parentheses)
  644. /*
  645. /* 1.  Filter sliding window of data to get 32 subband
  646. /* samples per channel.
  647. /* (window_subband,filter_subband)
  648. /*
  649. /* 2.  If joint stereo mode, combine left and right channels
  650. /* for subbands above #jsbound#.
  651. /* (*_combine_LR)
  652. /*
  653. /* 3.  Calculate scalefactors for the frame, and if layer 2,
  654. /* also calculate scalefactor select information.
  655. /* (*_scale_factor_calc)
  656. /*
  657. /* 4.  Calculate psychoacoustic masking levels using selected
  658. /* psychoacoustic model.
  659. /* (*_Psycho_One, psycho_anal)
  660. /*
  661. /* 5.  Perform iterative bit allocation for subbands with low
  662. /* mask_to_noise ratios using masking levels from step 4.
  663. /* (*_main_bit_allocation)
  664. /*
  665. /* 6.  If error protection flag is active, add redundancy for
  666. /* error protection.
  667. /* (*_CRC_calc)
  668. /*
  669. /* 7.  Pack bit allocation, scalefactors, and scalefactor select
  670. /* information (layer 2) onto bitstream.
  671. /* (*_encode_bit_alloc,*_encode_scale,II_transmission_pattern)
  672. /*
  673. /* 8.  Quantize subbands and pack them into bitstream
  674. /* (*_subband_quantization, *_sample_encoding)
  675. /*
  676. /************************************************************************/
  677.  
  678. main(argc, argv)
  679. int     argc;
  680. char    **argv;
  681. {
  682. typedef double SBS[2][3][SCALE_BLOCK][SBLIMIT];
  683.     SBS  FAR        *sb_sample;
  684. typedef double JSBS[3][SCALE_BLOCK][SBLIMIT];
  685.     JSBS FAR        *j_sample;
  686. typedef double IN[2][HAN_SIZE];
  687.     IN   FAR        *win_que;
  688. typedef unsigned int SUB[2][3][SCALE_BLOCK][SBLIMIT];
  689.     SUB  FAR        *subband;
  690.  
  691.     frame_params fr_ps;
  692.     layer info;
  693.     char original_file_name[MAX_NAME_SIZE];
  694.     char encoded_file_name[MAX_NAME_SIZE];
  695.     short FAR **win_buf;
  696. static short FAR buffer[2][1152];
  697. static unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT];
  698. static unsigned int scalar[2][3][SBLIMIT], j_scale[3][SBLIMIT];
  699. static double FAR ltmin[2][SBLIMIT], lgmin[2][SBLIMIT], max_sc[2][SBLIMIT];
  700.     FLOAT snr32[32];
  701.     short sam[2][1056];
  702.     int whole_SpF, extra_slot = 0;
  703.     double avg_slots_per_frame, frac_SpF, slot_lag;
  704.     int model, stereo, error_protection;
  705. static unsigned int crc;
  706.     int i, j, k, adb;
  707.     unsigned long bitsPerSlot, samplesPerFrame, frameNum = 0;
  708.     unsigned long frameBits, sentBits = 0;
  709.     unsigned long num_samples;
  710.  
  711. #ifdef  MACINTOSH
  712.     console_options.nrows = MAC_WINDOW_SIZE;
  713.     argc = ccommand(&argv);
  714. #endif
  715.  
  716.     /* Most large variables are declared dynamically to ensure
  717.        compatibility with smaller machines */
  718.  
  719.     sb_sample = (SBS FAR *) mem_alloc(sizeof(SBS), "sb_sample");
  720.     j_sample = (JSBS FAR *) mem_alloc(sizeof(JSBS), "j_sample");
  721.     win_que = (IN FAR *) mem_alloc(sizeof(IN), "Win_que");
  722.     subband = (SUB FAR *) mem_alloc(sizeof(SUB),"subband");
  723.     win_buf = (short FAR **) mem_alloc(sizeof(short *)*2, "win_buf");
  724.  
  725.     /* clear buffers */
  726.     memset((char *) buffer, 0, sizeof(buffer));
  727.     memset((char *) bit_alloc, 0, sizeof(bit_alloc));
  728.     memset((char *) scalar, 0, sizeof(scalar));
  729.     memset((char *) j_scale, 0, sizeof(j_scale));
  730.     memset((char *) scfsi, 0, sizeof(scfsi));
  731.     memset((char *) ltmin, 0, sizeof(ltmin));
  732.     memset((char *) lgmin, 0, sizeof(lgmin));
  733.     memset((char *) max_sc, 0, sizeof(max_sc));
  734.     memset((char *) snr32, 0, sizeof(snr32));
  735.     memset((char *) sam, 0, sizeof(sam));
  736.  
  737.     fr_ps.header = &info;
  738.     fr_ps.tab_num = -1;             /* no table loaded */
  739.     fr_ps.alloc = NULL;
  740.     info.version = MPEG_AUDIO_ID;
  741.  
  742.     programName = argv[0];
  743.     if(argc==1)     /* no command-line args */
  744.        obtain_parameters(&fr_ps, &model, &num_samples,
  745.              original_file_name, encoded_file_name);
  746.     else
  747.        parse_args(argc, argv, &fr_ps, &model, &num_samples,
  748.           original_file_name, encoded_file_name);
  749.     print_config(&fr_ps, &model, &num_samples,
  750.          original_file_name, encoded_file_name);
  751.  
  752.     hdr_to_frps(&fr_ps);
  753.     stereo = fr_ps.stereo;
  754.     error_protection = info.error_protection;
  755.  
  756.     if (info.lay == 1) { bitsPerSlot = 32; samplesPerFrame = 384;  }
  757.     else               { bitsPerSlot = 8;  samplesPerFrame = 1152; }
  758.     /* Figure average number of 'slots' per frame. */
  759.     /* Bitrate means TOTAL for both channels, not per side. */
  760.     avg_slots_per_frame = ((double)samplesPerFrame /
  761.                s_freq[info.sampling_frequency]) *
  762.               ((double)bitrate[info.lay-1][info.bitrate_index] /
  763.                (double)bitsPerSlot);
  764.     whole_SpF = (int) avg_slots_per_frame;
  765.     printf("slots/frame = %d\n",whole_SpF);
  766.     frac_SpF  = avg_slots_per_frame - (double)whole_SpF;
  767.     slot_lag  = -frac_SpF;
  768.     printf("frac SpF=%.3f, tot bitrate=%d kbps, s freq=%.1f kHz\n",
  769.        frac_SpF, bitrate[info.lay-1][info.bitrate_index],
  770.        s_freq[info.sampling_frequency]);
  771.  
  772.     if (frac_SpF != 0)
  773.        printf("Fractional number of slots, padding required\n");
  774.     else info.padding = 0;
  775.  
  776.     while (get_audio(musicin, buffer, num_samples, stereo, info.lay) > 0) {
  777.  
  778.        fprintf(stderr, "{%4lu}", frameNum++); fflush(stderr);
  779.        win_buf[0] = &buffer[0][0];
  780.        win_buf[1] = &buffer[1][0];
  781.        if (frac_SpF != 0) {
  782.       if (slot_lag > (frac_SpF-1.0) ) {
  783.          slot_lag -= frac_SpF;
  784.          extra_slot = 0;
  785.          info.padding = 0;
  786.          /*  printf("No padding for this frame\n"); */
  787.       }
  788.       else {
  789.          extra_slot = 1;
  790.          info.padding = 1;
  791.          slot_lag += (1-frac_SpF);
  792.          /*  printf("Padding for this frame\n");    */
  793.       }
  794.        }
  795.        adb = (whole_SpF+extra_slot) * bitsPerSlot;
  796.  
  797.        switch (info.lay) {
  798.  
  799. /***************************** Layer I **********************************/
  800.  
  801.       case 1 :
  802.          for (j=0;j<SCALE_BLOCK;j++)
  803.          for (k=0;k<stereo;k++) {
  804.         window_subband(&win_buf[k], &(*win_que)[k][0], k);
  805.         filter_subband(&(*win_que)[k][0], &(*sb_sample)[k][0][j][0]);
  806.          }
  807.  
  808.          I_scale_factor_calc(*sb_sample, scalar, stereo);
  809.          if(fr_ps.actual_mode == MPG_MD_JOINT_STEREO) {
  810.         I_combine_LR(*sb_sample, *j_sample);
  811.         I_scale_factor_calc(j_sample, &j_scale, 1);
  812.          }
  813.  
  814.          put_scale(scalar, &fr_ps, max_sc);
  815.  
  816.          if (model == 1) I_Psycho_One(buffer, max_sc, ltmin, &fr_ps);
  817.          else {
  818.         for (k=0;k<stereo;k++) {
  819.            psycho_anal(&buffer[k][0],&sam[k][0], k, info.lay, snr32,
  820.                    (FLOAT)s_freq[info.sampling_frequency]*1000);
  821.            for (i=0;i<SBLIMIT;i++) ltmin[k][i] = (double) snr32[i];
  822.         }
  823.          }
  824.  
  825.          I_main_bit_allocation(ltmin, bit_alloc, &adb, &fr_ps);
  826.  
  827.          if (error_protection) I_CRC_calc(&fr_ps, bit_alloc, &crc);
  828.  
  829.          encode_info(&fr_ps, &bs);
  830.  
  831.          if (error_protection) encode_CRC(crc, &bs);
  832.  
  833.          I_encode_bit_alloc(bit_alloc, &fr_ps, &bs);
  834.          I_encode_scale(scalar, bit_alloc, &fr_ps, &bs);
  835.          I_subband_quantization(scalar, *sb_sample, j_scale, *j_sample,
  836.                     bit_alloc, *subband, &fr_ps);
  837.          I_sample_encoding(*subband, bit_alloc, &fr_ps, &bs);
  838.          for (i=0;i<adb;i++) put1bit(&bs, 0);
  839.       break;
  840.  
  841. /***************************** Layer 2 **********************************/
  842.  
  843.       case 2 :
  844.          for (i=0;i<3;i++) for (j=0;j<SCALE_BLOCK;j++)
  845.         for (k=0;k<stereo;k++) {
  846.            window_subband(&win_buf[k], &(*win_que)[k][0], k);
  847.            filter_subband(&(*win_que)[k][0], &(*sb_sample)[k][i][j][0]);
  848.         }
  849.  
  850.         II_scale_factor_calc(*sb_sample, scalar, stereo, fr_ps.sblimit);
  851.         pick_scale(scalar, &fr_ps, max_sc);
  852.         if(fr_ps.actual_mode == MPG_MD_JOINT_STEREO) {
  853.            II_combine_LR(*sb_sample, *j_sample, fr_ps.sblimit);
  854.            II_scale_factor_calc(j_sample, &j_scale, 1, fr_ps.sblimit);
  855.         }       /* this way we calculate more mono than we need */
  856.             /* but it is cheap */
  857.  
  858.         if (model == 1) II_Psycho_One(buffer, max_sc, ltmin, &fr_ps);
  859.         else {
  860.            for (k=0;k<stereo;k++) {
  861.               psycho_anal(&buffer[k][0],&sam[k][0], k, 
  862.                  info.lay, snr32,
  863.                  (FLOAT)s_freq[info.sampling_frequency]*1000);
  864.               for (i=0;i<SBLIMIT;i++) ltmin[k][i] = (double) snr32[i];
  865.            }
  866.         }
  867.  
  868.         II_transmission_pattern(scalar, scfsi, &fr_ps);
  869.         II_main_bit_allocation(ltmin, scfsi, bit_alloc, &adb, &fr_ps);
  870.  
  871.         if (error_protection)
  872.            II_CRC_calc(&fr_ps, bit_alloc, scfsi, &crc);
  873.  
  874.         encode_info(&fr_ps, &bs);
  875.  
  876.         if (error_protection) encode_CRC(crc, &bs);
  877.  
  878.         II_encode_bit_alloc(bit_alloc, &fr_ps, &bs);
  879.         II_encode_scale(bit_alloc, scfsi, scalar, &fr_ps, &bs);
  880.         II_subband_quantization(scalar, *sb_sample, j_scale,
  881.                       *j_sample, bit_alloc, *subband, &fr_ps);
  882.         II_sample_encoding(*subband, bit_alloc, &fr_ps, &bs);
  883.         for (i=0;i<adb;i++) put1bit(&bs, 0);
  884.       break;
  885.  
  886. /***************************** Layer 3 **********************************/
  887.  
  888.       case 3 : break;
  889.  
  890.        }
  891.  
  892.        frameBits = sstell(&bs) - sentBits;
  893.        if(frameBits%bitsPerSlot)   /* a program failure */
  894.       fprintf(stderr,"Sent %ld bits = %ld slots plus %ld\n",
  895.           frameBits, frameBits/bitsPerSlot,
  896.           frameBits%bitsPerSlot);
  897.        sentBits += frameBits;
  898.  
  899.     }
  900.  
  901.     close_bit_stream_w(&bs);
  902.  
  903.     printf("Avg slots/frame = %.3f; b/smp = %.2f; br = %.3f kbps\n",
  904.        (FLOAT) sentBits / (frameNum * bitsPerSlot),
  905.        (FLOAT) sentBits / (frameNum * samplesPerFrame),
  906.        (FLOAT) sentBits / (frameNum * samplesPerFrame) *
  907.        s_freq[info.sampling_frequency]);
  908.  
  909.     if (fclose(musicin) != 0){
  910.        printf("Could not close \"%s\".\n", original_file_name);
  911.        exit(2);
  912.     }
  913.  
  914. #ifdef  MACINTOSH
  915.     set_mac_file_attr(encoded_file_name, VOL_REF_NUM, CREATOR_ENCODE,
  916.               FILETYPE_ENCODE);
  917. #endif
  918.  
  919.     printf("Encoding of \"%s\" with psychoacoustic model %d is finished\n",
  920.        original_file_name, model);
  921.     printf("The MPEG encoded output file name is \"%s\"\n",
  922.         encoded_file_name);
  923.     exit(0);
  924. }
  925.  
  926. /************************************************************************
  927. /*
  928. /* usage
  929. /*
  930. /* PURPOSE:  Writes command line syntax to the file specified by #stderr#
  931. /*
  932. /************************************************************************/
  933.  
  934. static void usage()  /* print syntax & exit */
  935. {
  936.     fprintf(stderr,
  937.     "usage: %s                         queries for all arguments, or\n",
  938.         programName);
  939.     fprintf(stderr,
  940.     "       %s [-l lay][-m mode][-p psy][-s sfrq][-b br][-d emp]\n",
  941.         programName);
  942.     fprintf(stderr,
  943.     "          [-c][-o][-e] inputPCM [outBS]\n");
  944.     fprintf(stderr,"where\n");
  945.     fprintf(stderr," -l lay   use layer <lay> coding   (dflt %4u)\n",DFLT_LAY);
  946.     fprintf(stderr," -m mode  channel mode : s/d/j/m   (dflt %4c)\n",DFLT_MOD);
  947.     fprintf(stderr," -p psy   psychoacoustic model 1/2 (dflt %4u)\n",DFLT_PSY);
  948.     fprintf(stderr," -s sfrq  input smpl rate in kHz   (dflt %4.1f)\n",DFLT_SFQ);
  949.     fprintf(stderr," -b br    total bitrate in kbps    (dflt %4u)\n",DFLT_BRT);
  950.     fprintf(stderr," -d emp   de-emphasis n/5/c        (dflt %4c)\n",DFLT_EMP);
  951.     fprintf(stderr," -c       mark as copyright\n");
  952.     fprintf(stderr," -o       mark as original\n");
  953.     fprintf(stderr," -e       add error protection\n");
  954.     fprintf(stderr," inputPCM input PCM sound file (standard or AIFF)\n");
  955.     fprintf(stderr," outBS    output bit stream of encoded audio (dflt inName+%s)\n",
  956.         DFLT_EXT);
  957.     exit(1);
  958. }
  959.  
  960. /************************************************************************
  961. /*
  962. /* aiff_check
  963. /*
  964. /* PURPOSE:  Checks AIFF header information to make sure it is valid.
  965. /*           Exits if not.
  966. /*
  967. /************************************************************************/
  968.  
  969. void aiff_check(file_name, pcm_aiff_data)
  970. char *file_name;          /* Pointer to name of AIFF file */
  971. IFF_AIFF *pcm_aiff_data;  /* Pointer to AIFF data structure */
  972. {
  973.  
  974. #ifdef IFF_LONG
  975.     if (pcm_aiff_data->sampleType != IFF_ID_SSND) {
  976. #else
  977.     if (strncmp(&pcm_aiff_data->sampleType,IFF_ID_SSND,4)) {
  978. #endif
  979.        printf("Sound data is not PCM in \"%s\".\n", file_name);
  980.        exit(1);
  981.     }
  982.  
  983.     if(SmpFrqIndex((long)pcm_aiff_data->sampleRate) < 0) {
  984.        printf("in \"%s\".\n", file_name);
  985.        exit(1);
  986.     }
  987.  
  988.     if (pcm_aiff_data->sampleSize != sizeof(short) * BITS_IN_A_BYTE) {
  989.     printf("Sound data is not %d bits in \"%s\".\n",
  990.            sizeof(short) * BITS_IN_A_BYTE, file_name);
  991.     exit(1);
  992.     }
  993.  
  994.     if (pcm_aiff_data->numChannels != MONO &&
  995.     pcm_aiff_data->numChannels != STEREO) {
  996.        printf("Sound data is not mono or stereo in \"%s\".\n", file_name);
  997.        exit(1);
  998.     }
  999.  
  1000.     if (pcm_aiff_data->blkAlgn.blockSize != 0) {
  1001.        printf("Block size is not %lu bytes in \"%s\".\n", 0, file_name);
  1002.        exit(1);
  1003.     }
  1004.  
  1005.     if (pcm_aiff_data->blkAlgn.offset != 0) {
  1006.        printf("Block offset is not %lu bytes in \"%s\".\n", 0, file_name);
  1007.        exit(1);
  1008.     }
  1009.  
  1010. }
  1011.